Component({
  // 设置上传区域的class，上传后的图片为当前区域大小
  externalClasses: ["ext-class"],
  properties: {
    url: {
      type: String,
      value: ""
    },
    mode: {
      type: String,
      value: "widthFix",
      options: ["scaleToFill", "aspectFit", "aspectFill", "widthFix", "top", "bottom", "center", "left", "right", "top left", "top right", "bottom left", "bottom right"]
    },
    preview: {
      type: Boolean,
      value: true
    },
    maxImageSize: {
      type: Number,
      value: 1e7
    }
  },
  data: {},
  methods: {
    onPreviewTap(e) {
      const url = this.data.url;

      // 由于&&前面成立才会执行后面语句
      // previewImage方法预览分辨率大的图片会无法预览，多点几次还会闪退
      // 实测红米K30 6400万像素照片闪退
      !0 === this.data.preview && wx.previewImage({
        current: url,
        urls: [url],
      })
    },
    onAddTap() {
      if (this.data.url) return;
      // 实测红米K30照片大都不是原图，稍大些的图片均被压缩
      wx.chooseImage({
        count: 1,
        sizeType: ['original'],
        sourceType: ["album", "camera"],
        success: res => {
          const url = res.tempFilePaths[0]
          const size = res.tempFiles[0].size

          // 当尺寸过大提醒父组件
          if (size > this.data.maxImageSize) {
            wx.showToast({
              icon: 'none',
              title: '图片尺寸过大，请上传10M以内的图片！',
            })
            return
          }
          this.setData({
            url
          })
          this.triggerEvent("add", {
            url
          })
        }
      })
    },
    onDelTap() {
      this.setData({
        url: ''
      })
      this.triggerEvent("remove")
    }
  }
});